import React, { useMemo } from "react";
import UserAvatar, { UserAvatarProps } from "../UserAvatar";
import "./style.less";
import { User } from "../../types/user";
import Icon from "@/utils/icons";
export interface AvatarGroupProps {
  /**
   * 用户列表
   */
  users: User[];
  /**
   * 最大显示的头像数量
   */
  maxCount?: number;
  /**
   * 头像尺寸
   */
  size?: UserAvatarProps["size"];
  /**
   * 头像形状
   */
  shape?: "circle" | "square";
  /**
   * 头像之间的重叠距离（负值表示重叠）
   */
  gap?: number;
  /**
   * 是否使用姓名缩写，默认使用最后一个字符
   */
  useAbbreviation?: boolean;
  /**
   * 自定义样式类
   */
  className?: string;
  /**
   * 点击头像的回调
   */
  onAvatarClick?: (user: User, index: number) => void;
  /**
   * 点击"更多"头像的回调
   */
  onMoreClick?: (restUsers: User[]) => void;
  /**
   * 是否显示头像边框
   * @default false
   */
  showBorder?: boolean;
  /**
   * 头像的颜色列表
   */
  colors?: string[] | string;
  /**
   * 是否始终显示 "更多" 的头像
   * @default false
   */
  alwaysShowDots?: boolean;
}

/**
 * 用户头像组组件
 * 可以显示多个用户头像，超过最大数量将显示三个点
 */
const AvatarGroup: React.FC<AvatarGroupProps> = ({
  users = [],
  maxCount = 8,
  size = "default",
  shape = "circle",
  gap = -8,
  useAbbreviation = false,
  className = "",
  onAvatarClick,
  onMoreClick,
  showBorder = false,
  colors,
  alwaysShowDots = false,
}) => {
  // 计算显示的用户和剩余数量
  const { displayUsers, restUsers, restCount } = useMemo(() => {
    if (users.length <= maxCount) {
      return { displayUsers: users, restUsers: [], restCount: 0 };
    }

    const display = users.slice(0, maxCount);
    const rest = users.slice(maxCount);
    return { displayUsers: display, restUsers: rest, restCount: rest.length };
  }, [users, maxCount]);

  // 计算头像大小
  const avatarSize = useMemo(() => {
    if (typeof size === "number") {
      return size;
    }
    const sizeMap = { small: 24, default: 28, large: 60 };
    return sizeMap[size as keyof typeof sizeMap] || 40;
  }, [size]);

  // 点击头像的处理函数
  const handleAvatarClick = (user: User, index: number) => {
    onAvatarClick?.(user, index);
  };

  // 点击"更多"的处理函数
  const handleMoreClick = () => {
    onMoreClick?.(restUsers);
  };

  const borderClass = showBorder ? "with-border" : "";

  return (
    <div
      className={`avatar-group ${className} ${borderClass}`}
      style={{ paddingRight: Math.abs(Math.min(0, gap)) }}
    >
      {/* 显示用户头像 */}
      {displayUsers.map((user, index) => (
        <div
          key={user.id}
          className={`avatar-item ${borderClass}`}
          style={{
            marginLeft: gap,
            zIndex: 2 + displayUsers.length - index,
          }}
          onClick={() => handleAvatarClick(user, index)}
        >
          <UserAvatar
            name={user.name}
            size={size}
            shape={shape}
            useAbbreviation={useAbbreviation}
            colors={colors}
          />
        </div>
      ))}

      {/* 显示超出数量的圆圈 */}
      {restCount > 0 && (
        <div
          className={`avatar-item avatar-rest-count ${borderClass}`}
          style={{
            marginLeft: gap,
            zIndex: 1,
          }}
        >
          <div
            className="rest-count-circle"
            style={{
              minWidth: avatarSize,
              height: avatarSize,
              lineHeight: `${avatarSize}px`,
              fontSize: avatarSize * 0.4,
            }}
          >
            +{restCount}
          </div>
        </div>
      )}

      {/* 显示更多(三个点)的头像 */}
      {(alwaysShowDots || restCount > 0) && (
        <div
          className={`avatar-item avatar-more ${borderClass}`}
          style={{
            marginLeft: gap,
            zIndex: 0,
          }}
          onClick={handleMoreClick}
          title={`还有${restCount}人`} // 添加悬停提示
        >
          <div
            className="dots-container"
            style={{
              width: avatarSize,
              height: avatarSize,
            }}
          >
            <Icon name="Dots" size={avatarSize * 0.5} />
          </div>
        </div>
      )}
    </div>
  );
};

export default AvatarGroup;
